<!--驾驶员信息-->
<template>
  <Layout>
    <Form ref="form1" :model="dataToQuery" :label-width="120">
      <Row class="query-form">
        <Col span="8">
          <FormItem label="二级集团：">
            <two-level-org org-code class="query-form-el" v-model="dataToQuery.twoLevelOrgCode"/>
          </FormItem>
        </Col>
        <Col span="8">
          <FormItem label="单位名称：" prop="order">
            <!--                        <cascader-dom class="query-form-el" ref='queryOrgCascader' @setOrgInfo='setQueryCompanyName' :orgTree="true" :setCurrentName="{label:dataToQuery.companyName,value:dataToQuery.companyId}"></cascader-dom>-->

            <Input class="query-form-el" type="text" v-model="dataToQuery.companyName"></Input>
          </FormItem>
        </Col>
        <Col span="8" v-if="!switchFlag">
          <Button @click="switchQuery(true)" class="ivu-btn-switch" type="text">展开∨</Button>
          <Button @click="reset" class="ivu-btn-reset">重置</Button>
          <Button type="primary" class="ivu-btn-query" icon="md-search" @click="query">查询</Button>
        </Col>
        <Col span="8" v-else>
          <FormItem label='驾驶证编号：' prop='driverNumber'>
            <Input class='query-form-el' placeholder="请填写驾驶证编号" type='text'
                   v-model='dataToQuery.driverNumber'></Input>
          </FormItem>
        </Col>
      </Row>
      <Row v-show="switchFlag" class="query-form">
        <Col span="8">
          <FormItem label='姓名：' prop='userName'>
            <Input class='query-form-el' placeholder="请填写姓名" type='text' v-model='dataToQuery.userName'></Input>
          </FormItem>
        </Col>
        <Col span="8">
          <FormItem label='联系电话：' prop='cellPhone'>
            <Input class='query-form-el' placeholder="请填写联系电话" type='text'
                   v-model='dataToQuery.cellPhone'></Input>
          </FormItem>
        </Col>
        <Col span="8">
          <Button @click="switchQuery(false)" class="ivu-btn-switch" type="text">收起∧</Button>
          <Button @click="reset" class="ivu-btn-reset">重置</Button>
          <Button class="ivu-btn-query" icon="md-search" @click="query">查询</Button>
        </Col>
      </Row>
      <Row class="query-form" v-if="!modelSelect">
        <Col span="24">
          <Button size="large" class="ivu-btn-add" icon="md-add" @click="addInfo">新增</Button>
          <Button size="large" class="ivu-btn-add" icon="md-download" @click="downloadDescriptionExcel">导出模板
          </Button>
          <Button size="large" class="ivu-btn-add" icon="md-cloud-upload" @click="beachUpload">批量导入</Button>
          <download-button :api="exportUrl" :query-form="dataToQuery"/>
          <!--<Button type="primary" class="ivu-btn-add" icon="md-cloud-download" @click="exportFormSubmit">导出</Button> -->
        </Col>
      </Row>
    </Form>
    <Table ref='table' :height="tableHeight" no-data-text="没有查询到相关数据!" @on-selection-change='getSelectRows'
           :loading='pageStatus.loading'
           @on-sort-change="sortChange" border :columns="columns1" :data="dataTable">
    </Table>
    <Row style="margin-right:10px;">
      <Col span="24">
        <Page style="float: right" :total="pagedata.total" :page-size="pagedata.pageSize" @on-change="pageChange"
              @on-page-size-change="pageSizeChange" :page-size-opts="pageSizeArray" show-total show-sizer
              show-elevator/>
      </Col>
    </Row>
    <Modal :title="this.getModalTitle('驾驶员信息')" :transfer=false :mask-closable="false" v-model="dialogShow"
           v-if="dataToView && dialogShow" :width=800 :styles="{maxHeight:'700px'}" class-name='limit-height-dialog'>
      <Row>
        <Col span="24">
          <Form ref="dialogForm" :class="mode === 'view'?'modal-view-detail':''" :show-message="false"
                :model="dataToView" :rules="mode === 'view'?{}:ruleCustom" :label-width="mode === 'view'?120:null"
                :label-position="mode === 'view'?'right':'top'">

            <Row type="flex" justify="space-around" class="code-row-bg">
              <Col span="23">
                <FormItem label='单位名称：' prop='companyId'>
                  <div v-if="mode === 'view'">{{ dataToView.companyName }}</div>
                  <!--<Input v-else class='query-form-el' placeholder="请填写单位名称" type='text' v-model='dataToView.companyId'></Input>-->
                  <div v-else>
                    <cascader-dom v-if="show" class='query-form-el' ref='orgCascader' @setOrgInfo='setCompanyId'
                                  @setOrgname="setCompanyName" :orgTree="true"
                                  :currentOrgId="dataToView.companyId" :rootOrgId="dataToView.belongOrgId"
                                  :setCurrentName="{label:dataToView.companyName,value:dataToView.companyId}"></cascader-dom>
                  </div>
                </FormItem>
              </Col>

            </Row>
            <Row type="flex" justify="space-around" class="code-row-bg">
              <Col span="11">
                <FormItem label='姓名：' prop='userName'>
                  <div v-if="mode === 'view'">{{ dataToView.userName }}</div>
                  <Input v-else class='query-form-el' placeholder="请填写姓名" type='text'
                         v-model='dataToView.userName'></Input>
                </FormItem>
              </Col>
              <Col span="11">
                <FormItem label='性别：' prop='gender'>
                  <div v-if="mode === 'view'">{{
                      dataToView.gender == 'M' ? '男' : dataToView.gender == 'F' ? '女' : '-'
                    }}
                  </div>
                  <Select v-else v-model='dataToView.gender' class='query-form-el'>
                    <Option value="M" lable="男">男</Option>
                    <Option value="F" lable="女">女</Option>
                  </Select>
                </FormItem>
              </Col>
            </Row>
            <Row type="flex" justify="space-around" class="code-row-bg">
              <Col span="11">
                <FormItem label='驾驶证编号：' prop='driverNumber'>
                  <div v-if="mode === 'view'">{{ dataToView.driverNumber }}</div>
                  <Input v-else class='query-form-el' placeholder="请填写驾驶证编号" type='text'
                         v-model='dataToView.driverNumber'></Input>
                </FormItem>
              </Col>
              <Col span="11">
                <FormItem label='联系电话：' prop='cellPhone'>
                  <div v-if="mode === 'view'">{{ dataToView.cellPhone }}</div>
                  <Input v-else class='query-form-el' placeholder="请填写联系电话" type='text'
                         v-model='dataToView.cellPhone'></Input>
                </FormItem>
              </Col>
            </Row>
            <Row type="flex" justify="space-around" class="code-row-bg">
              <Col span="11">
                <FormItem label='职务：' prop='position'>
                  <div v-if="mode === 'view'">{{ dataToView.position }}</div>
                  <Input v-else class='query-form-el' placeholder="请填写职务" type='text'
                         v-model='dataToView.position'></Input>
                </FormItem>
              </Col>
              <Col span="11">
                <FormItem label='准驾车型：' prop='driveType'>
                  <div v-if="mode === 'view'">{{ dataToView.driveType }}</div>
                  <Input v-else class='query-form-el' placeholder="请填写准驾车型" type='text'
                         v-model='dataToView.driveType'></Input>
                </FormItem>
              </Col>
            </Row>
            <Row type="flex" justify="space-around" class="code-row-bg">
              <Col span="11">
                <FormItem label='初次领证日期：' prop='beginDate'>
                  <div v-if="mode === 'view'">{{ renderViewDate(dataToView.beginDate) }}</div>
                  <DatePicker v-else class="query-form-el" placeholder="请选择初次领证日期"
                              v-model='dataToView.beginDate'></DatePicker>
                </FormItem>
              </Col>
              <Col span="11">
                <FormItem label='年审到期：' prop='deadline'>
                  <div v-if="mode === 'view'">{{ renderViewDate(dataToView.deadline) }}</div>
                  <DatePicker v-else class="query-form-el" placeholder="请选择年审到期"
                              v-model='dataToView.deadline'></DatePicker>
                </FormItem>
              </Col>
            </Row>
            <Row type="flex" justify="space-around" class="code-row-bg">
              <Col span="11">
                <FormItem label='填报人：' prop='createUserName'>
                  <div v-if="mode === 'view'">{{ dataToView.createUserName }}</div>
                  <Input v-else class='query-form-el' placeholder="请填写填报人" readonly type='text'
                         v-model='dataToView.createUserName'></Input>
                </FormItem>
              </Col>
              <Col span="11">
                <FormItem label='填报时间：' prop='createDate'>
                  <div v-if="mode === 'view'">{{ renderViewDate(dataToView.createDate) }}</div>
                  <DatePicker v-else class="query-form-el" placeholder="请选择填报时间" readonly
                              v-model='dataToView.createDate'></DatePicker>
                </FormItem>
              </Col>
            </Row>
            <!--<Row type="flex" justify="space-around" class="code-row-bg">-->
            <!--<Col span="11">-->
            <!--<FormItem label='填报人手机号：' prop='registrantPhone'>-->
            <!--<div v-if="mode === 'view'">{{ dataToView.registrantPhone }}</div>-->
            <!--<Input v-else class='query-form-el' placeholder="请填写填报人手机号" type='text' v-model='dataToView.registrantPhone'></Input>-->
            <!--</FormItem>-->
            <!--</Col>-->
            <!--<Col span="11"></Col>-->
            <!--</Row>-->

          </Form>
        </Col>
      </Row>
      <div slot="footer">
        <Button v-if="mode != 'view'" type="primary" class='ivu-btn-save' @click="submit('dialogForm')">确定</Button>
        <Button v-if="mode != 'view'" type="primary" class='ivu-btn-cancel' @click="handleCancel">取消</Button>
        <Button v-if="mode === 'view'" class='ivu-btn-save' @click="dialogShow=false">关闭</Button>
      </div>
    </Modal>

    <Modal :mask-closable="false" :transfer=false v-model="model3" :width=700 title="驾驶员信息导入"
           @on-cancel="cancelMap">
      <Form ref="map" :show-message="false" :model="map" label-position="top">
        <Row type="flex" justify="space-around" class="code-row-bg">
          <Col span="23">
            <FormItem label="" prop="file">
              <div>
                <Upload ref="upload1"
                        :before-upload="handleUpload "
                        :format="['xlsx', 'xls']"
                        accept=".xlsx, .xls"
                        :max-size="10240"
                        type="drag"
                        :action="uploadUrl">
                  <div style="padding: 10px">
                    <Icon type="ios-cloud-upload" size="45" style="color: #3399ff"></Icon>
                    <p>点击将文件拖拽到这里上传</p>
                    <span style="font-size:8px;color: #797a64">仅支持上传单个excel </span>
                  </div>
                </Upload>
              </div>
              <div v-if="fileTrue">
                <a>{{ map.file.name }}</a>
                <Button type="text" icon="md-trash" @click="map.file = {},fileTrue = false"
                        style="margin-left: 5px;margin-bottom: 3px"/>
              </div>
            </FormItem>
          </Col>
        </Row>
      </Form>
      <div slot="footer">
        <Button type="primary" class='ivu-btn-save' :disabled="uploadDissabled" @click="submitFile('map')">确定</Button>
        <Button type="primary" class='ivu-btn-cancel' @click="cancelMap">取消</Button>
      </div>
    </Modal>

    <Modal title="导入详情" v-model="logInfoModel" :transfer=false :mask-closable="false">
      <Row type="flex" justify="space-around" class="code-row-bg">
        <Col span="23">
          <div v-html="logInfo"></div>
        </Col>
      </Row>
      <div slot="footer">
        <Button type="primary" class='ivu-btn-cancel' @click="logInfoModel=false,logInfo=null">关闭</Button>
      </div>
    </Modal>
  </Layout>
</template>

<script>
import {Api} from '@/api/index.js'
import {formatDate} from '@/tools/index'

var cascaderDom = () => import('@/components/cascader-dom.vue');
import pageCommonFunction from '@/components/pageCommonFunction.js'
import {sessionStorage, cookie} from '@/common/cacheUtils.js';

export default {
  components: {cascaderDom},
  props: ['modelSelect'],
  data() {
    return {
      ...this.createCommonDataField(),
      imgUrl: "",
      columns1: [
        {title: '序号', width: 70, fixed: 'left', align: 'center', render: this.indexColumnsRender},
        {key: 'companyName', title: '单位名称', align: 'center', minWidth: 200,},
        {key: 'userName', title: '姓名', align: 'center', minWidth: 120,},
        {
          key: 'gender', title: '性别', align: 'center', minWidth: 120,
          render: (h, params) => {
            return h('span', params.row.gender == 'M' ? '男' : params.row.gender == 'F' ? '女' : '-')
          }
        },
        {key: 'driverNumber', title: '驾驶证编号', align: 'center', minWidth: 120,},
        {key: 'cellPhone', title: '联系电话', align: 'center', minWidth: 120,},
        {key: 'position', title: '职务', align: 'center', minWidth: 120,},
        {key: 'driveType', title: '准驾车型', align: 'center', minWidth: 120,},
        {
          key: 'beginDate',
          title: '初次领证日期',
          sortable: "custom",
          align: 'center',
          minWidth: 120,
          render: this.renderCellDate
        },
        {
          key: 'deadline',
          title: '年审到期',
          sortable: "custom",
          align: 'center',
          minWidth: 120,
          render: this.renderCellDate
        },
        {
          key: 'createDate',
          title: '填报时间',
          sortable: "custom",
          align: 'center',
          minWidth: 120,
          render: this.renderCellDate
        },
        // this.getActionColumns(),
        {
          title: '操作',
          key: 'action',
          fixed: 'right',
          width: this.modelSelect ? 80 : 160,
          align: 'center',
          render: (h, params) => {
            if (this.modelSelect) {
              return h('div', [
                h('A', {
                  props: {type: 'primary', size: 'small'},
                  style: {fontSize: '12px'},
                  on: {
                    click: () => {
                      // this.checkSave(params.row);
                      this.$emit('getSelectModelData', params.row);
                    }
                  }
                }, '选择'),
              ]);
            } else {
              if ((this.currentUser.loginId === this.Common.admin || this.currentUser.userId === params.row.createUserId || this.currentUser.userRole.find(obj => obj.roleId == '73b38b37dff64392ba0ee7dd579bf293') != undefined
                  || sessionStorage('userId').getObject('userId').userBeHandedOver.find(obj => obj == params.row.createUserId) != undefined)) {
                return h('div', [
                  h('A', {
                    props: {type: 'primary', size: 'small'},
                    style: {fontSize: '14px',},
                    on: {
                      click: () => {
                        this.viewData(params);
                      }
                    }
                  }, '详情'),
                  h('Divider', {props: {type: 'vertical'}}, ''),
                  h('A', {
                    props: {type: 'primary', size: 'small'},
                    disabled: true,
                    style: {fontSize: '14px'},
                    on: {
                      click: () => {
                        this.editData(params);
                      }
                    }
                  }, '修改'),
                  h('Divider', {props: {type: 'vertical'}}, ''),
                  h('A', {
                    props: {type: 'primary', size: 'small'},
                    style: {fontSize: '14px', color: 'red'},
                    on: {
                      click: () => {
                        this.deleteData(params);
                      }
                    }
                  }, '删除')
                ]);
              } else {
                return h('div', [
                  h('A', {
                    props: {type: 'primary', size: 'small'},
                    style: {fontSize: '14px',},
                    on: {
                      click: () => {
                        this.viewData(params);
                      }
                    }
                  }, '详情'),
                  h('Divider', {props: {type: 'vertical'}}, ''),
                  h('A', {
                    props: {type: 'primary', size: 'small'},
                    style: {fontSize: '14px', color: '#c5c8ce'}
                  }, '修改'),
                  h('Divider', {props: {type: 'vertical'}}, ''),
                  h('A', {
                    props: {type: 'primary', size: 'small'},
                    style: {fontSize: '14px', color: '#c5c8ce'}
                  }, '删除')
                ]);
              }
            }
          }
        },
      ],
      ruleCustom: {
        companyId: [{required: true, message: '请填写单位名称', trigger: 'change',}],
        userName: [{required: true, message: '请填写姓名', trigger: 'change',}],
        gender: [{required: true, message: '请填写性别', trigger: 'change',}],
        driverNumber: [{required: true, message: '请填写驾驶证编号', trigger: 'change',}],
        // cellPhone: [ { required: true, message: '请填写联系电话', trigger: 'change',}],
        position: [{required: true, message: '请填写职务', trigger: 'change',}],
        driveType: [{required: true, message: '请填写准驾车型', trigger: 'change',}],
        beginDate: [{required: true, message: '请填写初次领证日期', trigger: 'change', type: 'date'}],
        deadline: [{required: true, message: '请填写年审到期', trigger: 'change', type: 'date'}],
        createUserName: [{required: true, message: '请填写填报人', trigger: 'change',}],
        createDate: [{required: true, message: '请填写填报时间', trigger: 'change', type: 'date'}],
        cellPhone: [{
          validator: (rule, value, callback) => {
            if (!(/^1[3456789]\d{9}$/.test(this.dataToView.cellPhone))) {
              callback(' ');
              // this.$Message.error("请填写有效的的手机号")
            } else {
              callback()
            }
          },
          required: true,
          trigger: 'blur'
        }],
      },
      tableHeight: 10,
      dictMap: {},
      punishment: false,
      penaltyAmount: true,
      // api
      queryUrl: Api.querySaTraff.replace('{{table}}', 'carDriver'),
      exportUrl: Api.exportSaTraff.replace('{{table}}', 'carDriver'),
      deleteUrl: Api.deleteSaTraff.replace('{{table}}', 'carDriver'),
      getUrl: Api.getSaTraff.replace('{{table}}', 'carDriver'),
      updateUrl: Api.updateSaTraff.replace('{{table}}', 'carDriver'),
      saveUrl: Api.saveSaTraff.replace('{{table}}', 'carDriver'),
      uploadUrl: Api.uploadSaTraff.replace('{{table}}', 'carDriver'),

      currentUser: JSON.parse(sessionStorage('userId').get('userId')),

      twoLevel: [],
      show: true,

      fileTrue: false,
      map: {},
      model3: false,
      uploadDissabled: false,
      logInfoModel: false,
      logInfo: null
    }
  },
  async mounted() {
    this.setTableHeight();
    // this.selectSecGroupNames()
    this.query();
  },
  methods: {
    ...pageCommonFunction,
    submitFile(map) {
      this.$refs[map].validate((valid) => {
        if (valid) {
          this.uploadDissabled = true
          let formData = new FormData();
          formData.append("file", this.map.file);
          formData.append("createUserId", this.currentUser.userId);
          formData.append("createOrgId", this.currentUser.orgInfo.orgId);
          this.$http.post(this.uploadUrl, formData).then((res) => {
            this.uploadDissabled = false
            if (res.data.status == "200") {
              // this.$Message.success("驾驶员信息导入成功! 导入详情请查看控制台");
              this.logInfoModel = true
              this.logInfo = res.data.data
              this.query()
            } else {
              this.$Message.error(res.data.msg);
            }
            this.map = {}
            this.fileTrue = false
            this.model3 = false
          }).catch(e => {
            console.log(e);
            this.model3 = false
            this.map = {}
            this.uploadDissabled = false
            this.$Message.error("导入失败！请检查导入文档的格式是否正确");
          })
        } else {
          this.$Message.error('请填报完整!');
        }
      })

    },
    handleUpload(file) {
      this.map.file = file;
      this.fileTrue = true
      return false;
    },
    cancelMap() {
      this.model3 = false
      this.fileTrue = false
      this.map = {}
    },
    beachUpload() {
      this.model3 = true
      this.fileTrue = false
      this.map = {}
    },
    downloadDescriptionExcel() {
      this.$http.get(Api.templateDownload + '4', {
        responseType: 'blob'      //告诉服务器我们需要的响应格式
      }).then((res) => {
        const aLink = document.createElement("a");
        let blob = new Blob([res.data], {
          type: res.bodyBlob.type      //将会被放入到blob中的数组内容的MIME类型
        });
        aLink.href = URL.createObjectURL(blob)
        aLink.download = "驾驶员信息模板.xlsx" //标题
        aLink.click()
        document.body.appendChild(aLink)
      })
    },
    selectSecGroupNames() {
      this.$http.get(Api.quqeryTwoOrgInfo).then(res => {
        this.twoLevel = res.data.data
      }).catch(e => {
      })
    },
    deleteData(params) {
      this.deleteDateAjax(params);
    },
    query() {
      // if(this.dataToQuery.eventTypeIdsArrays) {
      //     this.dataToQuery.eventTypeIds = this.arrayToInFormat(this.dataToQuery.eventTypeIdsArrays)
      // }
      // this.dataToQuery.orgId = this.currentUser.companyId;
      this.queryAjax();
    },

    submit(name) {
      this.submitAjax(name);
    },
    createEmptyDataToAdd() {
      return {
        createDate: new Date(),
        createUserId: this.currentUser.userId,
        createUserName: this.currentUser.userName,
        id: this.get_uuid(),
        // idFiles:[],

      }
    },
    // async afterDataToViewInit() {
    //     await this.getFiles('id');
    // },
  },
  watch: {},
}
</script>

<style lang='css' scoped>
.ivu-form-item {
  padding-right: 20px;
}

.query-form-el, .ivu-date-picker, .ivu-input-wrapper {
  width: 100%;
}

</style>
